package com.zhudeshuai.zhudemolist.http;

import com.zhu.zhuCore.utils.LogUtil;
import com.zhudeshuai.zhudemolist.api.WeatherInfoApi;
import com.zhudeshuai.zhudemolist.bean.WeatherInfoResult;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 请求工具类
 *
 * @author zhudeshuai
 * @since 16/3/19
 */
public class RequestHelper {
    private static final String BASE_URL = "http://www.weather.com.cn/";
    private static final String TAG = "zhu";

    private RequestHelper() {
    }

    private static RequestHelper sInstance;
    private static Retrofit sRetrofit;

    public static RequestHelper getInstance() {
        if (sInstance == null) {
            synchronized (RequestHelper.class) {
                if (sInstance == null) {
                    sInstance = new RequestHelper();
                    OkHttpClient client = new OkHttpClient();
                    sRetrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .client(client)
                            .build();
                }
            }

        }
        return sInstance;
    }

    //    http://www.weather.com.cn/data/sk/101110101.html
    public void requestWeather(final IResponseCallback<WeatherInfoResult> callback) {
        WeatherInfoApi weatherInfoApi = sRetrofit.create(WeatherInfoApi.class);
        weatherInfoApi.getWeatherInfo("101110101")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WeatherInfoResult>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LogUtil.d(TAG, "onStart():" + Thread.currentThread().getName());
                    }

                    @Override
                    public void onCompleted() {
                        LogUtil.d(TAG, "onCompleted():" + Thread.currentThread().getName());
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d(TAG, "onError():" + Thread.currentThread().getName());
                    }

                    @Override
                    public void onNext(WeatherInfoResult weatherInfoResult) {
                        LogUtil.d(TAG, "onNext():" + Thread.currentThread().getName());
                    }
                });
    }


    public interface IResponseCallback<T> {
        void onSuccess(T t);

        void onFailed(Throwable throwable);
    }

}
